package Controller;

import Interceptor.MangerInterceptor;
import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.core.Path;
import pojo.Admin;
import pojo.User;

import java.util.List;

@Path("manger")
@Before(MangerInterceptor.class)
public class MangerController extends Controller {
    public void index(){
        render("index.html");
    }
    public void adminController(){
        List<Admin> admins = new Admin().dao().find("select * from admin order by id desc");
        set("admins",admins);
        render("admincontroller.html");
    }
    public void adminAddIndex(){
        render("adminadd.html");
    }
    public void adminadd(){
        String username = get("username");
        String pwd = get("password");
        String secpwd = get("secpassword");
        String nick = get("nick");
        List<Admin> admins = new Admin().dao().find("select * from admin where username = ?", username);
        if(!pwd.equals(secpwd)){
            set("errmsg","输入的密码不同！");
            forwardAction("/msg/errindex");
        }
        else if (admins.size() != 0){
            set("errmsg","账号已经存在！");
            forwardAction("/msg/errindex");
        }else{
            new Admin().set("username",username)
                    .set("pwd",pwd).set("nick",nick).save();
            redirect("/manger/adminController");
        }
    }
    public void delete(){
        String id = getPara(0);
        try {
            new Admin().dao().deleteById(id);
            redirect("/manger/adminController");
        }
        catch (Exception e){
            set("errmsg","删除失败");
            forwardAction("/msg/errindex");
        }
    }


    /**
     *  user
     */
    public void userController(){
        List<User> users = new User().dao().findAll();
        set("users",users);
        render("usercontroller.html");
    }
    /**
     * user add index
     */
    public void userAddIndex(){
        render("useradd.html");
    }
    /**
     * user add
     */
    public void useradd(){
        String name = get("name");
        String sex = get("sex");
        String age = get("age");
        String remark = get("remark");
        try {
            new User().set("name",name).set("age",age).set("sex",sex).set("remark",remark).save();
            redirect("/manger/userController");
        }
        catch (Exception e){
            set("errmsg","数据库出错");
            forwardAction("/msg/errindex");
        }
    }
    /**
     * user delete
     */
    public void userdelete(){
        String id = getPara(0);
        try {
            new User().dao().deleteById(id);
            redirect("/manger/userController");
        }
        catch (Exception e){
            set("errmsg","删除失败");
            forwardAction("/msg/errindex");
        }
    }
}
